package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.*;
import cn.wolfcode.luowowo.article.query.StrategyDetailQuery;
import cn.wolfcode.luowowo.article.query.StrategyQuery;
import cn.wolfcode.luowowo.article.service.*;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisVORedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.StrategySearchQuery;
import cn.wolfcode.luowowo.search.service.IStrategyTemplateSearchService;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("strategy")
public class StrategyController {

    @Reference
    private IStrategyService strategyService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IStrategyDetailService strategyDetailService;

    @Reference
    private IStrategyTagService strategyTagService;

    @Reference
    private IStrategyCommentService strategyCommentService;

    @Reference
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    @Reference
    private IStrategyCommendService strategyCommendService;

    @Reference
    private IStrategyTemplateSearchService strategyTemplateSearchService;

    @RequestMapping("searchPage")
    public String searchPage(@ModelAttribute("qo") StrategySearchQuery qo, Model model){
        Page query = strategyTemplateSearchService.query(qo);
        model.addAttribute("page", query);
        return "strategy/searchPageTpl";
    }

    @RequestMapping("")
    public String index(Model model){
        // commends 轮播图片
        List<StrategyCommend> commends = strategyCommendService.getTop5();
        model.addAttribute("commends", commends);
        // hotCds 热门攻略排行 : 阅读数 + 评论数前10名
        List<StrategyStatisVO> hotCds = strategyStatisVORedisService.listHotVOTop10();
        model.addAttribute("hotCds", hotCds);
        // 国内外攻略推荐排行 ：点赞数 + 收藏数在前10名
        // 具体步骤 ：1、查询所有 vokey 2、遍历分别拿国内 / 国外前 10 个 vo 对象
        String prefix = RedisKeys.STRATEGY_ZSET_SORT_COMMEND.getPrefix();
        List<StrategyStatisVO> vos = strategyStatisVORedisService.getAbroadStrategyStatisVOs(prefix);
        ArrayList<StrategyStatisVO> unabroadCds = new ArrayList<>(); // 国内
        ArrayList<StrategyStatisVO> abroadCds = new ArrayList<>(); // 国外

        for (StrategyStatisVO vo : vos) {
            if(vo.isIsabroad()){
                if(abroadCds.size() < 10){
                    abroadCds.add(vo);
                }
            }else {
                if(unabroadCds.size() < 10){
                    unabroadCds.add(vo);
                }
            }
        }

        // unabroadCds -- 国内
        model.addAttribute("unabroadCds", unabroadCds);
        // abroadCds -- 国外
        model.addAttribute("abroadCds", abroadCds);
        // themeCds
        model.addAttribute("themeCds", strategyTemplateSearchService.queryThemeTop10());
        // chinas
        model.addAttribute("chinas", strategyTemplateSearchService.queryConditionProvincesGroup());
        // abroads
        model.addAttribute("abroads", strategyTemplateSearchService.queryConditionAbroadsGroup());
        // themes
        model.addAttribute("themes", strategyTemplateSearchService.queryConditionThemeGroup());
        return "strategy/index";
    }


    // 攻略点赞（顶）
    @RequestMapping("strategyThumbup")
    @ResponseBody
    public Object strategyThumbup(Long sid, @UserParam UserInfo userInfo){
        // 1、登录后才能点赞
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(102); // data.code == 102
            return result;
        }
        Boolean ret = strategyStatisVORedisService.thumbup(sid, 1, userInfo.getId());

        if(ret){
            strategyStatisVORedisService.addCommendScore(sid, 1);
        }

        return new AjaxResult(ret, null)
                .addData(strategyStatisVORedisService.getStrategyStatisVo(sid)); // data.data.thumbsupnum

    }

    // 攻略文章收藏
    @RequestMapping("favor")
    @ResponseBody
    public Object favor(Long sid, @UserParam UserInfo userInfo){

        if(userInfo == null){
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(102);
            return result;
        }
        Boolean ret = strategyStatisVORedisService.favor(sid, 1, userInfo.getId());

        if(ret){
            strategyStatisVORedisService.addCommendScore(sid, 1);
        }else {
            strategyStatisVORedisService.addCommendScore(sid, -1);
        }

        return new AjaxResult(ret, null)
                .addData(strategyStatisVORedisService.getStrategyStatisVo(sid));
    }

    // 攻略评论点赞
    @RequestMapping("commentThumbUp")
    @ResponseBody
    public Object commentThumbUp(String toid, Long fromid){ // 评论 id \ 点赞人 id
        // 点赞、取消点赞 是同个请求，如何区分
        // 解决方案：把点赞人 id 存到 list 中，请求进来时，判断 该 用户 id 是否在 list 中存在
        // 存在就是取消点赞，把用户存到 list 中
        // 不存在就是 点赞，把用户从 list 中删除
        strategyCommentService.thumbUp(toid, fromid);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("detail")
    public String detail(Model model, Long id, @UserParam UserInfo userInfo){

        if(userInfo != null){
            Boolean isFavor = strategyStatisVORedisService.alreadyFavor(id, userInfo.getId());
            System.out.println(isFavor);
            model.addAttribute("isFavor", isFavor);
        }

        //detail
        StrategyDetail detail = strategyDetailService.get(id);
        StrategyContent content = strategyDetailService.getContent(id);
        detail.setStrategyContent(content);

        model.addAttribute("detail",detail);

        // vo
        model.addAttribute("vo", strategyStatisVORedisService.getStrategyStatisVo(id));

        return "strategy/detail";
    }

    @RequestMapping("commentAdd")
    @ResponseBody
    public Object commentAdd(Model model, StrategyComment strategyComment, @UserParam UserInfo userInfo){
        strategyComment.setUserId(userInfo.getId());
        strategyComment.setUsername(userInfo.getNickname());
        strategyComment.setCity(userInfo.getCity());
        strategyComment.setLevel(userInfo.getLevel());
        strategyComment.setHeadUrl(userInfo.getHeadImgUrl());
        strategyCommentService.saveOrUpdate(strategyComment);

        // 评论数加 1
        strategyStatisVORedisService.replyNumIncrease(strategyComment.getDetailId(), 1);
        strategyStatisVORedisService.addHotScore(strategyComment.getDetailId(), 1);

        int replynum = strategyStatisVORedisService.getStrategyStatisVo(strategyComment.getDetailId()).getReplynum();
        return AjaxResult.SUCCESS.addData(replynum);
    }

    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo")StrategyDetailQuery qo){
        //pageInfo
        model.addAttribute("pageInfo", strategyDetailService.query(qo));
        // toasts
        List<Destination> toasts = destinationService.getToasts(qo.getDestId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts", toasts);
        // dest
        model.addAttribute("dest", dest);
        // tags
        List<StrategyTag> tags = strategyTagService.list();
        model.addAttribute("tags", tags);

        return "strategy/list";
    }

    @RequestMapping("/getDestByDeep")
    @ResponseBody
    public Object getDestByDeep(int deep){
        return destinationService.getDestsByDeep(deep);
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Strategy  strategy){
        strategyService.saveOrUpdate(strategy);
        return AjaxResult.SUCCESS;
    }



    @RequestMapping("comment")
    public String comment(Model model, @ModelAttribute("qo") StrategyCommentQuery qo){
        Page query = strategyCommentService.query(qo);
        model.addAttribute("page", query);
        // 阅读数加一
        strategyStatisVORedisService.viewNumIncrease(qo.getDetailId(), 1);

        // 给热门排行加分
        strategyStatisVORedisService.addHotScore(qo.getDetailId(), 1);

        return "strategy/commentTpl";
    }

}
